import React, { useEffect, useMemo, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import request from "../../utils/request";
import MeidaCore from "../MeidaCore";
import { get, isEmpty, map } from "lodash";
import { Button, Card, Popover } from "antd";
import ImgCore from "../ImgCore";
import dynamic from "next/dynamic";
import { downloadLink } from "../../utils/download";
import LoadBtn from "../LoadBtn";
import Txt from "./Txt";

const AudioCore = dynamic(() => import("./AudioCore"), {
  ssr: false,
});

enum MediaType {
  element = "元素",
  face = "人物",
  logo = "图标",
  image = "图像",
  key_word = "关键词",
}

const DEFAULT_ACTIVE_IDX = "0-0-0";

const CaptchInfo: React.FC<{
  id: number;
}> = ({ id }) => {
  const [activeIdx, setActiveIdx] = useState(DEFAULT_ACTIVE_IDX);
  const isTouchActiveIdxRef = useRef(false);
  const [curMediaType, setCurMediaType] = useState<any>(null);
  const { data, isLoading } = useQuery({
    queryKey: [id],
    queryFn: async () => {
      const data = await request(`/task/${id}`);
      setCurMediaType(data?.media_type)
      return data;
    },
  });
  const defaultMediaType = data?.media_type;

  const activeItem = useMemo(() => {
    const [groupIdx, itemIdx, itemChildIdx] = activeIdx.split("-");
    return get(
      data,
      `pattern_info[${groupIdx}].pattern_detail_info[${itemIdx}].hit_info[${itemChildIdx}]`,
      {}
    );
  }, [data, activeIdx]);

  /**
   * 只在视屏类型或音屏类型时生效
   */
  const mediaHitTime =
    defaultMediaType === "video"
      ? activeItem.video_hit_time
      : activeItem.audio_hit_time;
  //
  // /**
  //  * 视屏类型在关键帧为空跳转为文本类型
  //  * defaultMediaType 和 mediaHitTime 在 isLoading 不变化时数据应已定义
  //  */
  // useEffect(() => {
  //   if (!isLoading) {
  //     if (defaultMediaType === "video" && isEmpty(activeItem.video_hit_time)) {
  //       setCurMediaType("doc");
  //     } else {
  //       setCurMediaType(defaultMediaType);
  //     }
  //   }
  // }, [isLoading]);

  /**
   * 媒体类型在关键帧为空跳转为文本类型
   */
  useEffect(() => {
    const mediaHitTime =
      defaultMediaType === "video"
        ? activeItem.video_hit_time
        : activeItem.audio_hit_time;
    if (
      !isLoading &&
      isTouchActiveIdxRef.current &&
      ["video", "audio"].includes(defaultMediaType)
    ) {
      setCurMediaType(get(mediaHitTime, 'length', 0) === 0 ? "doc" : defaultMediaType);
    }
  }, [activeIdx, isLoading, activeItem]);

  if (isLoading) return;

  const media_type = curMediaType;

  const isVideo = media_type === "video";
  // const isDoc = media_type === "doc" && real_media_type === "TXT";
  const isDoc = media_type === "doc";
  const isAudio = media_type === "audio";
  const isImage = media_type === "image";

  // doc 类型数据处理
  const textContent = get(data, "text_content.text_list", [])
    .map((item) => item?.content)
    .join("\r\n");
  const txtKeyWordList = get(activeItem, "doc_hit_content", []);
  // const txtKeyWordList = JSON.parse(activeItem.media_name);

  // console.log(activeItem)
  // console.log(curMediaType, media_type, real_media_type)
  // console.log(isDoc, textContent, txtKeyWordList);

  return (
    <div>
      <div className="flex">
        <div className="w-[700px]">
          {isAudio && (
            <AudioCore
              name={data.task_name}
              posterUrl={data.audio_cover_url}
              source={data.audio_url}
              pointList={activeItem.audio_hit_time}
            />
          )}
          {isVideo && (
            <MeidaCore
              showControl={true}
              type={isVideo ? "video" : "audio"}
              source={isVideo ? data.video_url : data.audio_url}
              pointList={mediaHitTime}
            />
          )}
          {isImage && (
            <ImgCore
              data={data.image_url}
              pointList={activeItem.image_hit_roi}
              activeItem={activeItem}
            />
          )}
          {isDoc && <Txt content={textContent} markList={txtKeyWordList} />}
        </div>
        <Card
          className="ml-[15px] flex w-[400px] flex-col"
          title={
            <div className="">
              <div className="float-right">
                <LoadBtn
                  size="small"
                  type="primary"
                  onClick={async () => {
                    const { url } = await request.post("/task/downloadMedia", {
                      media_id: [id],
                    });
                    downloadLink(url);
                  }}
                >
                  下载原文件
                </LoadBtn>
              </div>

              <div>
                <div className="mb-[5px] overflow-hidden text-ellipsis">
                  {data.task_name}
                </div>
                <Popover content={data.ori_file_name}>
                  <div className="overflow-hidden text-ellipsis whitespace-pre font-normal">
                    原始文件名：{data.ori_file_name}
                  </div>
                </Popover>
                <Popover content={data.ori_file_path}>
                  <div className="overflow-hidden text-ellipsis whitespace-pre font-normal">
                    原始文件路径：{data.ori_file_path}
                  </div>
                </Popover>
              </div>
            </div>
          }
          bodyStyle={{ overflowY: "auto", height: 343 }}
        >
          <div className="flex-1 overflow-auto">
            {map(data.pattern_info, (group, gIdx) => (
              <div className="my-[10px]">
                <div>
                  <span className="font-bold">{group.pattern_name}:</span>{" "}
                  {group.total_score}
                </div>
                {map(group.pattern_detail_info, (item, iIdx) => (
                  <div className="mt-[10px] flex">
                    <div
                      className="w-[50px]"
                      style={{ lineHeight: "32px", whiteSpace: "nowrap" }}
                    >
                      {MediaType[item.media_type]}：
                    </div>
                    <div className="m-[-5px]">
                      {map(item.hit_info, (item_child, item_childIdx) => (
                        <Button
                          className="m-[5px]"
                          type={
                            `${gIdx}-${iIdx}-${item_childIdx}` === activeIdx
                              ? "primary"
                              : "default"
                          }
                          danger={
                            `${gIdx}-${iIdx}-${item_childIdx}` === activeIdx
                          }
                          onClick={() => {
                            setActiveIdx(`${gIdx}-${iIdx}-${item_childIdx}`);
                            isTouchActiveIdxRef.current = true;
                          }}
                        >
                          {item_child.media_name}
                        </Button>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            ))}
          </div>
        </Card>
      </div>
      {["video", "audio"].includes(defaultMediaType) && (
        <div className="absolute left-[30px] bottom-[30px]">
          <Button
            className="float-left mr-[12px]"
            type="primary"
            onClick={() => {
              setCurMediaType(
                media_type === defaultMediaType ? "doc" : defaultMediaType
              );
            }}
          >
            ASR 展示
          </Button>
        </div>
      )}
    </div>
  );
};

export default CaptchInfo;
